package com.bingo.rbac.service.impl;

import com.bingo.rbac.common.ServerResponse;
import com.bingo.rbac.dto.SysDeptDto;
import com.bingo.rbac.exception.ParamException;
import com.bingo.rbac.mapper.SysDeptMapper;
import com.bingo.rbac.param.SysDeptParam;
import com.bingo.rbac.pojo.SysDept;
import com.bingo.rbac.service.SysDeptService;
import com.bingo.rbac.util.BeanValidator;
import com.bingo.rbac.util.LevelUtil;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 部门service
 *
 * @author bingo
 * @create 2017-12-03 14:21
 **/

@Service("sysDeptServiceImpl")
public class SysDeptServiceImpl implements SysDeptService {
    @Autowired
    private SysDeptMapper sysDeptMapper;

    private Logger logger = LoggerFactory.getLogger(SysDeptServiceImpl.class);

    @Override
    public ServerResponse saveDept(SysDeptParam sysDeptParam) {
        //BeanValidator.check(sysDeptParam);
        if (checkExist(sysDeptParam.getParentId(), sysDeptParam.getName())) {
            throw new ParamException("该部门下存在相同名称部门 ");
        }
        SysDept sysDept = new SysDept();
        sysDept.setName(sysDeptParam.getName());
        sysDept.setParentId(sysDeptParam.getParentId());
        sysDept.setRemark(sysDeptParam.getRemark());
        sysDept.setSeq(sysDeptParam.getSeq());
        logger.info("sysDept" + sysDept);
        String parentLevel = sysDeptMapper.getLevel(sysDept.getParentId());
        sysDept.setLevel(LevelUtil.getLevel(parentLevel, sysDept.getParentId()));
        sysDept.setOperateTime(new Date());
        sysDept.setCreateTime(new Date());
        sysDept.setUpdateTime(new Date());
        sysDept.setOperator("bingo");
        sysDept.setOperateIp("192.168.78.123");
        sysDeptMapper.insert(sysDept);

        return ServerResponse.createServerResponseBySuccess("增加部门成功");
    }
    public ServerResponse<List<SysDept>> getDeptZtree() {
        List<SysDept> sysDepts = sysDeptMapper.selectAll();
        return ServerResponse.createServerResponseBySuccess((sysDepts));
    }
    @Override
    public ServerResponse<List<SysDeptDto>> getDeptTree() {
        List<SysDept> sysDepts = sysDeptMapper.selectAll();
        Multimap multimap = ArrayListMultimap.create();
        List<SysDeptDto> sysDeptDtos = Lists.newArrayList();
        for (SysDept sysDept : sysDepts) {
            SysDeptDto sysDeptDto = SysDeptDto.adapt(sysDept);
            sysDeptDtos.add(sysDeptDto);
        }
        logger.info("部门长度-------"+sysDeptDtos.size());
        return ServerResponse.createServerResponseBySuccess(deptListToTree(sysDeptDtos));
    }
    /**不仅要更新自己，还要更新子节点*/
    public ServerResponse updateTree(SysDeptParam sysDeptParam) {
        BeanValidator.check(sysDeptParam);
        if (checkExist(sysDeptParam.getParentId(), sysDeptParam.getName())) {
            throw new ParamException("该部门下存在相同名称部门 ");
        }
        //更新之前的
        SysDept oldSysDept = sysDeptMapper.selectByPrimaryKey(sysDeptParam.getId());

        SysDept sysDept = new SysDept();
        sysDept.setName(sysDeptParam.getName());
        sysDept.setParentId(sysDeptParam.getParentId());
        sysDept.setRemark(sysDeptParam.getRemark());
        sysDept.setSeq(sysDeptParam.getSeq());
        logger.info("sysDept" + sysDept);
        String parentLevel = sysDeptMapper.getLevel(sysDept.getParentId());
        sysDept.setLevel(LevelUtil.getLevel(parentLevel, sysDept.getParentId()));
        sysDept.setOperateTime(new Date());
        sysDept.setCreateTime(new Date());
        sysDept.setUpdateTime(new Date());
        sysDept.setOperator("bingo");
        sysDept.setOperateIp("192.168.78.123");
        sysDeptMapper.insert(sysDept);

        return ServerResponse.createServerResponseBySuccess("更新部门成功");
    }

    //递归更新level
    public void  updateChild(SysDept oldSysDept,SysDept newSysDept){
    String childLevel = LevelUtil.getLevel(oldSysDept.getLevel(),oldSysDept.getId());
    List<SysDept>  childList = sysDeptMapper.selectDeptVoByLevel(childLevel);
    if(childList.size()!=0) {
        for (SysDept childDept : childList) {
            String parentLevel = sysDeptMapper.getLevel(newSysDept.getParentId());
            String newChildLevel = LevelUtil.getLevel(parentLevel, newSysDept.getParentId());
            childDept.setLevel(newChildLevel);
            SysDept sysDeptTemp = sysDeptMapper.selectByPrimaryKey(childDept.getId());
            sysDeptMapper.updateByPrimaryKey(childDept);

        }
    }

    }
    /**
     * 0.1----->      obj1
     * 0.2----->      obj2
     * 0.2.2--->      obj3
     */
    public List<SysDeptDto> deptListToTree(List<SysDeptDto> sysDeptDtoList) {
        Multimap multimap = ArrayListMultimap.create();
        List<SysDeptDto> rootList = Lists.newArrayList();
        for (SysDeptDto sysDeptDto : sysDeptDtoList) {
            multimap.put(sysDeptDto.getLevel(), sysDeptDto);
            logger.info("level：" + sysDeptDto.getLevel() + "部门名称" + sysDeptDto.getName() + "deptid" + sysDeptDto.getParentId());
            if (LevelUtil.ROOT.equals(sysDeptDto.getLevel())) {
                rootList.add(sysDeptDto);
            }
        }
        logger.info("multimap length"+multimap.size());
        tranFormToTree(multimap, rootList);
        logger.info("rootListSize" + rootList.size());
        return rootList;
    }

    /**获取每层元素*/
    public void tranFormToTree(Multimap levelMultimap, List<SysDeptDto> rootList) {
        SysDeptDto sysDeptDto = new SysDeptDto();
        for (SysDeptDto deptDto : rootList) {
            //获取子元素的level
            String nextLevel = LevelUtil.getLevel(deptDto.getLevel(), deptDto.getId());
            logger.info("nextLevel:" + nextLevel);
            List<SysDept> childDeptList = sysDeptMapper.selectDeptVoByLevel(nextLevel);
            List<SysDeptDto> tempList = (List<SysDeptDto>) levelMultimap.get(nextLevel);
            if (tempList.size() != 0) {
                for (SysDeptDto test : tempList) {
                    logger.info("testDto:" + test.getName() + test.getLevel());
                }
                deptDto.setList(tempList);
                tranFormToTree(levelMultimap, tempList);
            }

        }

    }


    public boolean checkExist(Integer parentId, String name) {
        SysDept sysDept = sysDeptMapper.selectDeptByDeptName(parentId, name);
        return sysDept == null ? false : true;
    }

}
